package hgz.stu.review.ruijie.config;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Properties;

import org.springframework.core.io.Resource;

import hgz.stu.review.ruijie.config.merge.ConfigMerger;
import hgz.stu.review.ruijie.config.resolve.ConfigResolver;
import hgz.stu.review.ruijie.enviroment.SkyEngineEnvType;

/**
 * Description: Function Description
 * Copyright: Copyright (c) 2017
 * Company: Ruijie Co., Ltd.
 * Create Time: 2018/8/30
 *
 * @author dell
 */
public class ModuleConfigFacade implements ConfigFacade {

    private List<ConfigResolver> configLoaderStrategies;

    private ConfigMerger configMerger;

    private String moduleName;

    public ModuleConfigFacade(List<ConfigResolver> configLoaderStrategies, ConfigMerger configMerger, String moduleName){
        this.configLoaderStrategies = configLoaderStrategies;
        this.configMerger = configMerger;
        this.moduleName = moduleName;
    }

    @Override
    public Properties getConfig(SkyEngineEnvType engineEnvType) {
        //资源定位
        Resource[] resources = findResources(engineEnvType);

        List<Properties> properties = convertToProperties(resources);

        return configMerger.merge(properties);
    }

    private List<Properties> convertToProperties(Resource[] resources) {
        return null;
    }

    private Resource[] findResources(SkyEngineEnvType skyEngineEnvType) {

        List<Resource> resourceList = new ArrayList<>();
        configLoaderStrategies.sort(Comparator.comparingInt(ConfigResolver::getOrder));

        for (ConfigResolver configResolver : configLoaderStrategies) {
            if(configResolver.containsConfig()){
                List<Resource> resources = configResolver.resolveModuleResource(skyEngineEnvType, moduleName);
                resourceList.addAll(resources);
            }

        }

        return resourceList.stream().toArray(Resource[]::new);
    }
}
